import { ReactElement, createContext, useReducer, Dispatch } from "react"

import reducer, { Iaction } from "./store/todoReducer"

//state类型

export type Istate = {
    data: Array<{
        id: string,
        completed: boolean,
        todo: string
    }>;
    copyData?: Istate['data'],
    activeButton: string
}

//声明初始化的状态

let initialState: Istate = {
    activeButton: 'all',
    data: [
        {
            id: Math.random().toString(16).slice(2),
            completed: false,
            todo: '吃饭'
        },
        {
            id: Math.random().toString(16).slice(2),
            completed: true,
            todo: '写代码'
        }
    ],
    copyData: [
        {
            id: Math.random().toString(16).slice(2),
            completed: false,
            todo: '吃饭'
        },
        {
            id: Math.random().toString(16).slice(2),
            completed: true,
            todo: '写代码'
        }
    ]
}


//2.创建context

//声明context的类型

type Icontext = {
    state: Istate;
    dispatch: Dispatch<Iaction>
}

let AppContext = createContext<Icontext>({} as Icontext)


let AppProvider = (props: { children: ReactElement }) => {

    //3.使用useReducer将state,dispatch传递给AppContext.Provider

    let [state, dispatch] = useReducer(reducer, initialState)

    return (
        <AppContext.Provider value={{ state, dispatch }}>
            {props.children}
        </AppContext.Provider>
    )
}


export {
    AppProvider as default,
    AppContext
}